package com.jingxuan.controller;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jingxuan.common.result.Result;
import com.jingxuan.common.result.ResultCode;
import com.jingxuan.dto.request.RecordBrowseBehaviorRequest;
import com.jingxuan.dto.request.RecordSearchBehaviorRequest;
import com.jingxuan.dto.response.BrowseHistoryResponse;
import com.jingxuan.interceptor.AuthInterceptor;
import com.jingxuan.service.UserBehaviorService;
import com.jingxuan.util.UserBehaviorAlgorithm.BrowseRecord;
import com.jingxuan.util.UserBehaviorAlgorithm.SearchRecord;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户行为上报接口。
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/behavior")
public class UserBehaviorController {

    @Autowired
    private UserBehaviorService userBehaviorService;

    /**
     * 记录用户搜索行为。
     */
    @PostMapping("/search")
    public Result<Void> recordSearchBehavior(@Valid @RequestBody RecordSearchBehaviorRequest request) {
        SearchRecord record = SearchRecord.builder()
            .userId(request.getUserId())
            .keyword(request.getKeyword())
            .timestamp(request.getTimestamp() != null ? request.getTimestamp() : LocalDateTime.now())
            .clicked(Boolean.TRUE.equals(request.getClicked()))
            .clickedProductId(request.getClickedProductId())
            .clickRank(request.getClickRank())
            .build();
        userBehaviorService.recordSearchBehavior(record);
        log.debug("已记录搜索行为，userId={}, keyword={}", record.getUserId(), record.getKeyword());
        return Result.success();
    }

    /**
     * 记录用户浏览行为。
     */
    @PostMapping("/browse")
    public Result<Void> recordBrowseBehavior(@Valid @RequestBody RecordBrowseBehaviorRequest request) {
        BrowseRecord record = BrowseRecord.builder()
            .userId(request.getUserId())
            .productId(request.getProductId())
            .productName(null)
            .category(request.getCategory())
            .brand(request.getBrand())
            .price(request.getPrice())
            .positiveRate(request.getPositiveRate())
            .heat(request.getHeat())
            .releaseTime(request.getReleaseTime())
            .startTime(request.getStartTime())
            .endTime(request.getEndTime())
            .pageDepth(request.getPageDepth())
            .pageCount(request.getPageCount())
            .build();
        userBehaviorService.recordBrowseBehavior(record);
        log.debug("已记录浏览行为，userId={}, productId={}", record.getUserId(), record.getProductId());
        return Result.success();
    }

    /**
     * 获取用户浏览历史。
     */
    @GetMapping("/browse/history")
    public Result<BrowseHistoryResponse> getBrowseHistory(@RequestParam(value = "limit", required = false) Integer limit) {
        Long userId = AuthInterceptor.getCurrentUserId();
        if (userId == null) {
            return Result.error(ResultCode.UNAUTHORIZED, "请先登录");
        }
        int resolvedLimit = (limit == null || limit <= 0) ? 30 : Math.min(limit, 100);
        BrowseHistoryResponse response = userBehaviorService.getBrowseHistory(userId, resolvedLimit);
        log.info("获取浏览历史，userId={}, limit={}, total={}", userId, resolvedLimit, response.getTotal());
        return Result.success("获取浏览历史成功", response);
    }
}
